﻿using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Security.Cryptography;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;


namespace TTQT.TTQT_Code
{
    /// <summary>
    /// Summary description for TTQTCommon.
    /// </summary>
    public class TTQTCommon
    {
        //public const string delete_Confirm = "javascript:return confirm(' Ban co chac chan muon xoa? ');";
        //public const string huyDuyet_Confirm = "javascript:return confirm(' Ban co chac chan muon huy duyet? ');";
        //public const string huyGiaoDich_Confirm = "javascript:return confirm(' Ban co chac chan muon huy giao dich? ');";
        //public const string guiHoSo_Confirm = "javascript:return confirm(' Ban co chac muon gui giao dich? ');";
        //public const string phanCong_Confirm = "javascript:return confirm(' Ban co chac muon phan cong nguoi nay? ');";
        //public const string alert_ThemThanhCongChungTu = "<script language =\"javascript\">\n alert(\"Thêm chứng từ thành công!\");\n </script>";
        //public const string alert_ThemCTKhongThanhCong = "<script language =\"javascript\">\n alert(\"Thêm chứng từ không thành công!\");\n </script>";
        //public const string alert_SoBanGocSai = "<script language =\"javascript\">\n alert(\"Số bản gốc sai!\");\n </script>";
        //public const string alert_SoBanSaoSai = "<script language =\"javascript\">\n alert(\"Số bản sao sai!\");\n </script>";
        //public const string alert_SoBanNNSai = "<script language =\"javascript\">\n alert(\"Số bản Non-Negative sai!\");\n </script>";
        //public const string alert_SoBanPhoToSai = "<script language =\"javascript\">\n alert(\"Số bản phô tô sai!\");\n </script>";
        //public const string alert_SoBanSai = "<script language =\"javascript\">\n alert(\"Phải có ít nhất 1 bản chứng từ!\");\n </script>";
        //public const string alert_SoTienSai = "<script language =\"javascript\">\n alert(\"Số tiền nhập không đúng!\");\n </script>";
        //public const string alert_SaiFormatNgay = "<script language =\"javascript\">\n alert(\"Ngày không đúng định dạng dd/mm/yyyy!\");\n </script>";
        //public const string alert_ChuaCoChungTu = "<script language =\"javascript\">\n alert(\"Hồ sơ chưa có chứng từ!\");\n </script>";
        //public const string alert_NhapSaiNgay = "<script language =\"javascript\">\n alert(\"Nhập sai ngày!\");\n </script>";
        //public const string alert_ThieuFielMatTruoc = "<script language =\"javascript\">\n alert(\"Chưa có File mặt trước!\");\n </script>";
        //public const string alert_LuuHSThanhCong = "<script language =\"javascript\">\n alert(\"Lưu hồ sơ thành công!\");\n </script>";
        //public const string alert_LuuHSKhongThanhCong = "<script language =\"javascript\">\n alert(\"Lưu hồ sơ không thành công!\");\n </script>";
        //public const string alert_DayDuyetHSThanhCong = "<script language =\"javascript\">\n alert(\"Đẩy duyệt hồ sơ thành công!\");\n </script>";
        //public const string alert_ThieuTenCT = "<script language =\"javascript\">\n alert(\"Thiếu tên chứng từ!\");\n </script>";
        //public const string alert_KhongNhapTTTraoDoi = "<script language =\"javascript\">\n alert(\"Chưa nhập thông tin!\");\n </script>";
        //public const string alert_TrungThamChieuSIBS = "<script language =\"javascript\">\n alert(\"Số tham chiếu SIBS này đã dùng cho giao dịch khác!\");\n </script>";
        //public const string alert_KhongNhapSoThamChieuSIBS = "<script language =\"javascript\">\n alert(\"Chưa nhập số tham chiếu SIBS!\");\n </script>";
        //public const string alert_KhongNhapSoSuKien = "<script language =\"javascript\">\n alert(\"Chưa nhập số sự kiện SIBS của giao dịch!\");\n </script>";
        //public const string alert_KhongCoThamChieuSIBS = "<script language =\"javascript\">\n alert(\"Số tham chiếu SIBS này không tồn tại!\");\n </script>";
        //public const string alert_XungDotThamChieuSIBS = "<script language =\"javascript\">\n alert(\"Số tham chiếu SIBS này đã dùng cho giao dịch khác!\");\n </script>";
        //public const string admin_Prefix = "TTQT_Administrator_";
        //public const string log_DangNhap = "DangNhap";
        //public const string log_Thoat = "Thoat";
        //public const string logXoaKhaiBaoDauKy = "DelKhaiBaoTon";

        //public const string log_LoiTruyXuatDuLieu = "Error while accessing data";
        //public const string log_DoiMatKhau = "DoiMatKhau";
        //public const string log_TaoMoiUser = "TaoMoiUser";
        //public const string log_SuaNguoiDung = "SuaNguoiDung";
        //public const string log_XoaNguoiDung = "XoaNguoiDung";
        //public const string log_GuiTinNhan = "GuiTinNhan";

        //public const string log_TaoGiaoDich = "TaoGiaoDich";
        //public const string log_SuaGiaoDich = "SuaGiaoDich";
        //public const string log_XoaGiaoDich = "XoaGiaoDich";
        //public const string log_DayDuyetGiaoDich = "DayDuyet";
        //public const string log_DuyetGiaoDich = "Duyet";//Duyệt
        //public const string log_TuChoiDuyet = "TuChoiDuyet";//Huỷ duyệt
        //public const string log_HuyGiaoDich = "HuyGiaoDich";//Huỷ giao dịch
        //public const string log_XemGiaoDich = "XemGiaoDich";
        //public const string log_GuiGDDenTTQT = "GuiGDDenTTQT";
        //public const string Log_PhanCongGiaoDich = "PhanCongGiaoDich";
        //public const string log_GanSoThamChieu = "GanSoThamChieu";//Gán tham chiếu

        //public const string log_ThemChiNhanh = "ThemChiNhanh";
        //public const string log_SuaChiNhanh = "SuaChiNhan";

        //public const string log_Type_SynPrdCod = "SynPrdCod";
        //public const string tran_Status_TaoMoi = "01";
        //public const string tran_Status_DayDuyet = "02";
        //public const string tran_Status_Duyet = "03";
        //public const string tran_Status_HuyDuyet = "04";
        //public const string tran_Status_GuiToiCNTTQT = "05";
        //public const string tran_Status_NhanGiaoDich = "06";
        //public const string tran_Status_PhanCongGiaoDich = "07";
        //public const string tran_Status_ThucHienGiaoDich = "08";
        //public const string Tran_Status_DaBiXoa = "09";//thực hiện bởi TTVCNN
        //public const string Tran_Status_HuyGD = "18";//thực hiện tại TTQT
        /// <summary>
        /// Xóa các ký tự đặc biệt khỏi xâu
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RemoveSpecialCharacters(string str)
        {
            return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
        }
        public static string GetDataString2(string sql)
        {
            string s = "";
            SqlConnection conn = new SqlConnection(TTQTCommon.DBConnectionString);
            conn.Open();
            SqlCommand comm = new SqlCommand(sql, conn);
            SqlDataReader dr = comm.ExecuteReader();
            if (dr.Read())
            {

                s = dr[0].ToString();
            }
            conn.Close();
            return s;
        }
        #region Authentication methods

        //public static bool IsAuthenticated()
        //{
        //    HttpContext context = HttpContext.Current;
        //    return
        //        context.User.Identity.IsAuthenticated && (context.User.Identity.Name.IndexOf(admin_Prefix) != -1);
        //}

        //public static void LoginUser(string userName, bool rememberAccount)
        //{
        //    LogoutUser();
        //    FormsAuthentication.Initialize();
        //    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, admin_Prefix + userName, DateTime.Now, DateTime.Now.AddMinutes(45), rememberAccount, "", FormsAuthentication.FormsCookiePath);
        //    Trace.Write(FormsAuthentication.FormsCookiePath + FormsAuthentication.FormsCookieName);
        //    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
        //    HttpContext.Current.Response.SetCookie(cookie);
        //}

        //public static void LogoutUser()
        //{
        //    HttpContext.Current.Items.Remove("ADMIN_INFO");
        //    HttpContext.Current.Session.Abandon();
        //    FormsAuthentication.SignOut();
        //}
        //member
        //public static void SetAuthenticateMember(string userName)
        //{
        //    HttpContext context = HttpContext.Current;
        //    if (context.Session["Member"] == null)
        //        context.Session.Add("Member", userName);
        //    else
        //        context.Session["Member"] = userName;
        //}

        #endregion

        #region Utilities methods
        public static string formatDateInReport(string dateFull)
        {
            try
            {
                return dateFull.Substring(0, 10);
            }
            catch (Exception ex)
            {

                return dateFull;
            }
        }
        public static string formatTien_KhongThapPhan(string strNumber)
        {
            try
            {
                string str;
                if (!string.IsNullOrEmpty(strNumber))
                {
                    str = ToStringCurrency(strNumber).ToString().Trim();
                    str = str.Substring(0, str.LastIndexOf('.'));
                    return str;
                }
                return string.Empty;
            }
            catch (Exception ex)
            {
                return strNumber;
            }
        }
        /// <summary>
        /// Hàm này để cắt ra tên file từ một đường dẫn đầy đủ
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string getFullFileName(string filePath)
        {
            int start = filePath.LastIndexOf(@"\") + 1;
            int end = filePath.Length - start;
            //return start.ToString() + " - " + end.ToString();
            return filePath.Substring(start, end);

        }

        /// <summary>
        /// Chuyển một chuỗi kiểu dd/MM/yyyy thành dd-MMM-yyyy
        /// </summary>
        /// <param name="dateAsDDMMYYYY"></param>
        /// <returns></returns>
        public static string convertDateString(string dateAsDDMMYYYY)
        {
            string result = "";
            string[] dmy = null;
            try
            {
                DateTime temp = Convert.ToDateTime(dateAsDDMMYYYY.Trim());
            }
            catch (Exception xxx)
            {
                return "";
            }
            if (dateAsDDMMYYYY.IndexOf("/") != -1)
            {
                dmy = dateAsDDMMYYYY.Split('/');
            }
            if (dateAsDDMMYYYY.IndexOf("-") != -1)
            {
                dmy = dateAsDDMMYYYY.Split('-');
            }
            if (dmy.Length >= 3)
            {
                result = dmy[0] + "-";
                result += convertMonth(dmy[1]) + "-";
                result += dmy[2];
            }
            else
            {
                return "";
            }
            return result;
        }
        /// <summary>
        /// Convert tháng từ số sang chuỗi
        /// </summary>
        /// <param name="monthInt"></param>
        /// <returns></returns>
        private static string convertMonth(string monthInt)
        {
            int month = int.Parse(monthInt);
            switch (month)
            {
                case 1:
                    return "jan";
                case 2:
                    return "feb";
                case 3:
                    return "mar";
                case 4:
                    return "apr";
                case 5:
                    return "may";
                case 6:
                    return "jun";
                case 7:
                    return "jul";
                case 8:
                    return "aug";
                case 9:
                    return "sep";
                case 10:
                    return "oct";
                case 11:
                    return "nov";
                case 12:
                    return "dec";
            }
            return "";
        }
        /// <summary>
        /// Chuyển một chuỗi ngày dạng dd-MMM-yyyy thành dd/MM/yyyy
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string convertDateString2(string input)
        {
            string result = "";
            try
            {
                result = input.Replace(input.Substring(3, 3), convertMonth2(input.Substring(3, 3))).Replace('-', '/');
            }
            catch
            {
                return "";
            }
            return result;
        }
        /// <summary>
        /// Convert tháng từ chuỗi sang số
        /// </summary>
        /// <param name="strMonth"></param>
        /// <returns></returns>
        private static string convertMonth2(string strMonth)
        {
            switch (strMonth)
            {
                case "jan":
                    return "01";
                case "feb":
                    return "02";
                case "mar":
                    return "03";
                case "apr":
                    return "04";
                case "may":
                    return "05";
                case "jun":
                    return "06";
                case "jul":
                    return "07";
                case "aug":
                    return "08";
                case "sep":
                    return "09";
                case "oct":
                    return "10";
                case "nov":
                    return "11";
                case "dec":
                    return "12";
            }
            return "";
        }
        public static string ToStringCurrency(string str)
        {
            string ret = "";
            //Thao.Nguyen added 20100715
            //Check null and empty input str
            if (string.IsNullOrEmpty(str))
                return string.Empty;
            decimal value = Convert.ToDecimal(str);
            CultureInfo culture = new CultureInfo("en-US");
            if (value >= 0)
                ret = String.Format(value.ToString("C", culture)).Remove(0, 1);
            else
            {
                decimal d = value * (-1M);
                ret = "-" + String.Format(d.ToString("C", culture)).Remove(0, 1);

            }
            return ret;
        }
        public static string ToStringFloat(string str)
        {
            string ret = "";
            float value = ToFloat(str);
            CultureInfo culture = new CultureInfo("en-US");
            if (value >= 0)
                ret = String.Format(value.ToString("C", culture)).Remove(0, 1);
            else
            {
                float d = value * (-1);
                ret = "-" + String.Format(d.ToString("C", culture)).Remove(0, 1);
            }
            return ret;
        }
        public static decimal ToDecimal(string str)
        {
            decimal ret = 0;
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
            NumberStyles styles;
            styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
               NumberStyles.Float;
            try
            {
                ret = Decimal.Parse(str, styles);
            }
            catch
            {
                ret = 0;
            }
            return ret;
        }
        public static string getTableNameTtqt_File()
        {
            return "ttqt_File" + DateTime.Now.Year.ToString();

        }
        public static string getTableName_PhanCong()
        {
            return "ttqt_PhanCong" + DateTime.Now.Year.ToString();
        }
        public static string getTableName_Assign(int year)
        {
            return "ttqt_Assign" + year.ToString();
        }
        public static string getTableName_GuiHS()
        {
            return "ttqt_GuiHS" + DateTime.Now.Year.ToString();
        }
        public static string getTableNameTtqt_Tran()
        {
            return "ttqt_Tran" + DateTime.Now.Year.ToString();
        }
        public static string getTableNameTtqt_Tran(int year)
        {
            return "ttqt_Tran" + year.ToString();
        }
        public static string getTableNameTtqt_log()
        {
            return "ttqt_Log" + DateTime.Now.ToString("yyyyMMdd").Substring(0, 6);
        }
        public static DataSet getDataSet(string sql)
        {
            DataSet ds = new DataSet();
            SqlConnection conn = new SqlConnection(TTQTCommon.DBConnectionString);
            conn.Open();
            SqlDataAdapter aDapt = new SqlDataAdapter();

            SqlCommand comm = new SqlCommand(sql, conn);
            aDapt.SelectCommand = comm;
            aDapt.Fill(ds, "tb");
            conn.Close();
            return ds;
        }

        /// <summary>
        /// Thao.Nguyen added 20100715
        /// Lay thong tin cac an chi bi mat
        /// </summary>
        /// <param name="userID"></param>
        /// <returns>DataSet</returns>
        public static DataTable GetDataTableForAnChiMat(string userID, string makho, bool toanHeThong)
        {
            SqlConnection sqlConn = new SqlConnection(TTQTCommon.DBConnectionString);
            SqlCommand sqlComm;
            sqlComm = toanHeThong ? new SqlCommand("Get_BaoCaoAnChiBiMat", sqlConn) : new SqlCommand("Get_BaoCaoAnChiBiMatTaiChiNhanh", sqlConn);
            try
            {
                DataTable dt = new DataTable();
                sqlComm.CommandType = CommandType.StoredProcedure;
                sqlComm.Parameters.AddWithValue("@UserId", userID);
                sqlComm.Parameters.AddWithValue("@MaKho", makho);
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlComm);
                sqlConn.Open();
                sqlDataAdapter.Fill(dt);
                sqlConn.Close();
                sqlComm.Dispose();
                return dt;
            }
            catch (Exception ex)
            {
                sqlConn.Close();
                sqlComm.Dispose();
                return null;
            }
        }

        /// <summary>
        /// Thao.Nguyen created 20100825
        /// Lấy dữ liệu cho báo cáo tiêu hủy ấn chỉ
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="makho"></param>
        /// <returns></returns>
        public static DataTable GetDataTableForTieuHuyAnChi(string userID, string makho, bool toanHeThong)
        {
            SqlConnection sqlConn = new SqlConnection(DBConnectionString);
            SqlCommand sqlComm;
            sqlComm = toanHeThong ? new SqlCommand("Get_BaoCaoTieuHuyAnChi", sqlConn) : new SqlCommand("Get_BaoCaoTieuHuyAnChiChiNhanh", sqlConn);
            try
            {
                DataTable dt = new DataTable();
                sqlComm.CommandType = CommandType.StoredProcedure;
                sqlComm.Parameters.AddWithValue("@UserId", userID);
                sqlComm.Parameters.AddWithValue("@MaKho", makho);
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlComm);
                sqlConn.Open();
                sqlDataAdapter.Fill(dt);
                sqlConn.Close();
                sqlComm.Dispose();
                return dt;
            }
            catch (Exception ex)
            {
                sqlConn.Close();
                sqlComm.Dispose();
                return null;
            }
        }

        /// <summary>
        /// Thao.Nguyen created 20100827
        /// Lấy dữ liệu cho báo cáo tồn kho ấn chỉ
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="makho"></param>
        /// <returns></returns>
        public static DataTable GetDataTableForBaoCaoTonKhoAnChi(string userID, string makho)
        {
            SqlConnection sqlConn = new SqlConnection(DBConnectionString);
            SqlCommand sqlComm = new SqlCommand("Get_BaoCaoTonKhoAnChi", sqlConn);
            try
            {
                DataTable dt = new DataTable();
                sqlComm.CommandType = CommandType.StoredProcedure;
                sqlComm.Parameters.AddWithValue("@UserID", userID);
                sqlComm.Parameters.AddWithValue("@MaKho", makho);
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlComm);
                sqlConn.Open();
                sqlDataAdapter.Fill(dt);
                sqlConn.Close();
                sqlComm.Dispose();
                return dt;
            }
            catch (Exception ex)
            {
                sqlConn.Close();
                sqlComm.Dispose();
                return null;
            }
        }

        /// <summary>
        /// Thao.Nguyen added 20100719
        /// To get datatable from database for bao cao an chi mau toan he thong
        /// </summary>
        /// <param name="userID"></param>
        /// <returns>DataTable</returns>
        public static DataTable GetDataTableForBaoCaoAnChiMauToanHeThong(bool anChiThuong, string loaiAnChi, string loaitien)
        {
            SqlConnection sqlConn = new SqlConnection(TTQTCommon.DBConnectionString);
            SqlCommand sqlComm = new SqlCommand("Get_BaoCaoAnChiMauToanHeThong_New", sqlConn);
            try
            {
                DataTable dt = new DataTable();
                sqlComm.CommandType = CommandType.StoredProcedure;
                sqlComm.Parameters.AddWithValue("@TinhChatAnChi", !anChiThuong ? 0 : 1);
                sqlComm.Parameters.AddWithValue("@LoaiAnChi", loaiAnChi);
                sqlComm.Parameters.AddWithValue("@LoaiTien", loaitien);
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlComm);
                sqlConn.Open();
                sqlDataAdapter.Fill(dt);
                sqlConn.Close();
                sqlComm.Dispose();
                return dt;
            }
            catch (Exception ex)
            {
                sqlConn.Close();
                sqlComm.Dispose();
                return null;
            }
        }

        /// <summary>
        /// Thao.Nguyen created
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="makho"></param>
        /// <returns></returns>
        public static DataTable GetDataForBaoCaoAnChiMauChiNhanh(string makho, string loaiTien)
        {
            SqlConnection sqlConn = new SqlConnection(TTQTCommon.DBConnectionString);
            //SqlCommand sqlComm = new SqlCommand("Get_BaoCaoAnChiMauChiNhanh", sqlConn);
            SqlCommand sqlComm = new SqlCommand("Get_BaoCaoAnChiMauChiNhanh_New", sqlConn);
            try
            {
                DataTable dt = new DataTable();
                sqlComm.CommandType = CommandType.StoredProcedure;
                sqlComm.Parameters.AddWithValue("@MaKho", makho);
                sqlComm.Parameters.AddWithValue("@LoaiTien", loaiTien);
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlComm);
                sqlConn.Open();
                sqlDataAdapter.Fill(dt);
                sqlConn.Close();
                sqlComm.Dispose();
                return dt;
            }
            catch (Exception ex)
            {
                sqlConn.Close();
                sqlComm.Dispose();
                return null;
            }
        }
        public static string cleanSQL(string sql)
        {
            string kq = sql.ToLower();
            try
            {
                kq = kq.Replace("insert", "");
                kq = kq.Replace("delete", "");
                kq = kq.Replace("alter", "");
                kq = kq.Replace("update", "");
                kq = kq.Replace("select", "");
                kq = kq.Replace("drop", "");
                kq = kq.Replace("truncate", "");
                //kq = kq.Replace("table", "");
                kq = kq.Replace("--", "");
            }catch(Exception ex)
            {
                
            }
            return kq;
        }
        public static bool sqlHopLe(string sql)
        {
            bool kq = true;
            if (sql.Contains("--"))
                kq = false;
            return kq;
        }
        #endregion

        #region Converting methods
        public static int ToInt32(object o, int _default)
        {
            int ret = _default;
            try
            {
                ret = Convert.ToInt32(o);
            }
            catch
            {
                ret = _default;
            }
            return ret;
        }
        public static string LoaiTienQD(object o)
        {
            string ret = string.Empty;
            string loaitien = string.Empty;
            try
            {
                loaitien = o.ToString();
                if (loaitien != "AAA")
                {
                    ret = " Số tiền (" + loaitien + ")";
                }
            }
            catch
            {
                ret = string.Empty;
            }
            return ret;
        }
        public static string ToString(object o)
        {
            string ret = string.Empty;
            try
            {
                ret = o.ToString();
            }
            catch
            {
                ret = string.Empty;
            }
            return ret;
        }

        public static decimal ToDecimal(object o, decimal _default)
        {
            decimal ret = _default;
            try
            {
                ret = Convert.ToDecimal(o);
            }
            catch
            {
                ret = _default;
            }
            return ret;
        }
        public static float ToFloat(object o)
        {
            try
            {
                return float.Parse(o.ToString());
            }
            catch (Exception ex)
            {
                return 0;
            }
        }
        public static float ToFloat(object o,float _default)
        {
            float ret = _default;
            try
            {
                ret = float.Parse(o.ToString());
            }
            catch
            {
                ret = _default;
            }
            return ret;
        }
        public static DateTime ToDateTime(object o)
        {
            DateTime ret = DateTime.Now;
            try
            {
                ret = Convert.ToDateTime(o);
            }
            catch
            {
                ret = DateTime.Now;
            }
            return ret;
        }

        public static DateTime ToDateTime(object o, DateTime d)
        {
            string format = "d/M/yyyy";
            CultureInfo en = new CultureInfo("en-US");
            Thread.CurrentThread.CurrentCulture = en;
            DateTime ret = d;
            try
            {
                ret = DateTime.ParseExact(o.ToString(), format, en.DateTimeFormat);
            }
            catch
            {
                ret = d;
            }
            return ret;
        }

        public static bool ToBoolean(object o, bool _default)
        {
            bool ret = _default;
            try
            {
                ret = Convert.ToBoolean(o);
            }
            catch
            {
                ret = _default;
            }
            return ret;
        }

        public static string ReFormat(string sDate)
        {
            string result = "";
            string[] temp = sDate.Split('-');
            switch (temp[1])
            {
                case "jan":
                    result = temp[0] + " / 01 /" + temp[2];
                    break;
                case "feb":
                    result = temp[0] + " / 02 /" + temp[2];
                    break;
                case "mar":
                    result = temp[0] + " / 03 /" + temp[2];
                    break;
                case "apr":
                    result = temp[0] + " / 04 /" + temp[2];
                    break;
                case "may":
                    result = temp[0] + " / 05 /" + temp[2];
                    break;
                case "jun":
                    result = temp[0] + " / 06 /" + temp[2];
                    break;
                case "jul":
                    result = temp[0] + " / 07 /" + temp[2];
                    break;
                case "aug":
                    result = temp[0] + " / 08 /" + temp[2];
                    break;
                case "sep":
                    result = temp[0] + " / 09 /" + temp[2];
                    break;
                case "oct":
                    result = temp[0] + " / 10 /" + temp[2];
                    break;
                case "nov":
                    result = temp[0] + " / 11 /" + temp[2];
                    break;
                case "dec":
                    result = temp[0] + " / 12 /" + temp[2];
                    break;
            }
            return result;
        }

        /// <summary>
        /// Thao.Nguyen created 20100825
        /// Dùng để định dạng số
        /// </summary>
        /// <param name="strNumber"></param>
        /// <returns></returns>
        public static string ToNumberFormat(string strNumber)
        {
            try
            {
                string str;
                if (!string.IsNullOrEmpty(strNumber))
                {
                    if (strNumber.Equals("0"))
                        return string.Empty;
                    str = ToStringCurrency(strNumber).ToString().Trim();
                    str = str.Substring(0, str.LastIndexOf('.'));
                    return str;
                }
                return string.Empty;
            }
            catch (Exception ex)
            {
                return strNumber;
            }
        }

        #endregion

        #region Encryption methods
        public static string MD5Encrypt(string plainText)
        {
            byte[] data, output;
            UTF8Encoding encoder = new UTF8Encoding();
            MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider();

            data = encoder.GetBytes(plainText);
            output = hasher.ComputeHash(data);

            return BitConverter.ToString(output).Replace("-", "").ToLower();
        }
        #endregion

        #region Working with Web.config

        public static string DBConnectionString
        {
            get { return ConfigurationSettings.AppSettings["TTQT.DataAccess.ConnectionString"]; }
        }
        public static string TTQTWebHomePath
        {
            get { return ConfigurationSettings.AppSettings["TTQTWebHomePath"]; }
        }

        public string TTQTWebServicePath
        {
            get { return ConfigurationSettings.AppSettings["WebServicePath"]; }
        }
        public static string SIBSdataConnectionString
        {
            get
            {
                string SIBSconnectionString = ConfigurationSettings.AppSettings["TTQT.DataAccess.SIBSConnectionString"];
                DataTable SIBSdata = DataAccessObject.instance().getSysvarSIBSdata();
                //IP, library, user, pass
                string IP = SIBSdata.Rows[0][0].ToString();
                string ODBCdata = SIBSdata.Rows[0][1].ToString();
                string user = SIBSdata.Rows[0][2].ToString();
                string pass = SIBSdata.Rows[0][3].ToString();
                SIBSconnectionString =
                    SIBSconnectionString.Replace("IP", IP).Replace("ODBCdata", ODBCdata).Replace("user", user).Replace("pass", pass);
                return SIBSconnectionString;
            }
        }
        public static string SIBSparaConnectionString
        {
            get
            {
                string SIBSconnectionString = ConfigurationSettings.AppSettings["TTQT.DataAccess.SIBSConnectionString"];
                DataTable SIBSdata = DataAccessObject.instance().getSysvarSIBSpara();
                //IP, library, user, pass
                string IP = SIBSdata.Rows[0][0].ToString();
                string ODBCdata = SIBSdata.Rows[0][1].ToString();
                string user = SIBSdata.Rows[0][2].ToString();
                string pass = SIBSdata.Rows[0][3].ToString();
                SIBSconnectionString =
                    SIBSconnectionString.Replace("IP", IP).Replace("ODBCdata", ODBCdata).Replace("user", user).Replace("pass", pass);
                return SIBSconnectionString;
            }
        }
        #endregion

        #region Methods for Web UI
        /// <summary>
        /// chuyển các item đã chọn sang và xóa khỏi nguồn
        /// </summary>
        /// <param name="lstSource"></param>
        /// <param name="lstDestination"></param>
        public static void moveSelectedItem(ListBox lstSource, ListBox lstDestination)
        {
            //Chuyển các item đã chọn sang listbox đích
            string values = "";
            foreach (ListItem item in lstSource.Items)
            {
                if (item.Selected && !lstDestination.Items.Contains(item))
                {
                    lstDestination.Items.Add(item);
                    values += item.Value;
                }
            }
            //Xóa các item đã chọn khỏi lstSource
            while (lstSource.SelectedIndex != -1)
            {
                lstSource.Items.RemoveAt(lstSource.SelectedIndex);
            }
        }
        /// <summary>
        /// Chuyển sang nhưng không xóa khỏi nguồn
        /// </summary>
        /// <param name="lstSource"></param>
        /// <param name="lstDestination"></param>
        public static void addSelectedItem(ListBox lstSource, ListBox lstDestination)
        {
            //Add các item đã chọn sang listbox đích
            string values = "";
            foreach (ListItem item in lstSource.Items)
            {
                if (item.Selected && !lstDestination.Items.Contains(item))
                {
                    lstDestination.Items.Add(item);
                    values += item.Value;
                }
            }
            //Xóa các item đã chọn khỏi lstSource
            //while (lstSource.SelectedIndex != -1)
            //{
            //    lstSource.Items.RemoveAt(lstSource.SelectedIndex);
            //}
        }
        /// <summary>
        /// Xóa các item đã chọn
        /// </summary>
        /// <param name="lstSource"></param>
        public static void removeSelectedItems(ListBox lstSource)
        {
            while (lstSource.SelectedIndex != -1)
            {
                lstSource.Items.RemoveAt(lstSource.SelectedIndex);
            }
        }
        /// <summary>
        /// Lấy các giá trị trong listbox và chuyển thành chuỗi mỗi giá trị cách nhau dấu phẩy
        /// </summary>
        /// <param name="lst">Listbox cần lấy giá trị</param>
        /// <param name="isIntValue">Nếu là các giá trị là kiểu số thì không cộng thêm dấu nháy đơn bao quanh, còn nếu là chuỗi thì phải thêm nháy đơn bao quanh để phù hợp khi dùng điều kiện "in" trong sql</param>
        /// <returns>Là chuỗi có dạng (gt1,gt2,gt3) với dấu cách ở cuối.</returns>
        public static string getAllValueOfListBox(ListBox lst, bool isIntValue)
        {
            if (lst.Items.Count <= 0)
            {
                return "";
            }
            string result = "";
            StringBuilder b = new StringBuilder();
            b.Append("(");
            if (isIntValue)
            {
                foreach (ListItem item in lst.Items)
                {
                    b.Append(item.Value.Trim());
                    b.Append(",");
                }
            }
            else
            {
                foreach (ListItem item in lst.Items)
                {
                    //result += "'" + item.Value.Trim() + "',";
                    b.Append("'");
                    b.Append(item.Value.Trim());
                    b.Append("',");

                }
            }
            result = b.ToString();
            result = result.Substring(0, result.Length - 1) + ") ";
            return result;
        }
        #endregion

        /// <summary>
        /// Hàm này lấy danh sách các giao dịch cần làm để đưa lên trang chủ
        /// </summary>
        /// <returns></returns>
        public static DataTable GetSoLuongAnChi(string makho,string userName)
        {
            SqlConnection sqlConn = new SqlConnection(TTQTCommon.DBConnectionString);
            SqlCommand sqlComm = new SqlCommand("GetSoLuongAnChi", sqlConn);
            try
            {
                DataTable dt = new DataTable();
                sqlComm.CommandType = CommandType.StoredProcedure;
                sqlComm.Parameters.AddWithValue("@UserName", userName);
                sqlComm.Parameters.AddWithValue("@MaKho", makho);
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlComm);
                sqlConn.Open();
                sqlDataAdapter.Fill(dt);
                sqlConn.Close();
                sqlComm.Dispose();
                return dt;
            }
            catch (Exception ex)
            {
                sqlConn.Close();
                sqlComm.Dispose();
                return null;
            }
        }
        public static string isNull(object input,string _default)
        {
            if(input==null)
            {
                return _default;
            }
            return input.ToString();
        }
    }
}